package com.shlh.saas.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shlh.saas.common.Result;
import com.shlh.saas.common.UserContext;
import com.shlh.saas.entity.ExportRecord;
import com.shlh.saas.service.ExportRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

/**
 * 导出记录控制器
 */
@Slf4j
@RestController
@RequestMapping("/export-records")
public class ExportRecordController {
    
    @Autowired
    private ExportRecordService exportRecordService;
    
    @Value("${export.file.path:/data/export}")
    private String exportFilePath;
    
    /**
     * 分页获取当前用户的导出记录
     *
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @return 导出记录分页数据
     */
    @GetMapping("/list")
    public Result<Map<String, Object>> getExportRecords(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        
        Long userId = UserContext.getUserId();
        
        try {
            Page<ExportRecord> page = new Page<>(pageNum, pageSize);
            IPage<ExportRecord> pageData = exportRecordService.getExportRecordsByUserId(page, userId);
            
            Map<String, Object> result = new HashMap<>();
            result.put("records", pageData.getRecords());
            result.put("total", pageData.getTotal());
            result.put("pages", pageData.getPages());
            result.put("current", pageData.getCurrent());
            result.put("size", pageData.getSize());
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取用户导出记录失败: " + e.getMessage(), e);
            return Result.error("获取导出记录失败");
        }
    }
    
    /**
     * 下载导出的文件
     *
     * @param id 导出记录ID
     * @return 文件下载响应
     */
    @GetMapping("/download/{id}")
    public ResponseEntity<Resource> downloadExportFile(@PathVariable Long id) {
        try {
            // 获取当前用户ID
            Long userId = UserContext.getUserId();
            
            // 获取导出记录
            ExportRecord exportRecord = exportRecordService.getById(id);
            
            // 检查记录是否存在且属于当前用户
            if (exportRecord == null) {
                return ResponseEntity.notFound().build();
            }
            
            if (!exportRecord.getUserId().equals(userId)) {
                return ResponseEntity.badRequest().build();
            }
            
            // 构建文件路径
            String filePath = exportFilePath + exportRecord.getFilePath();
            Path path = Paths.get(filePath);
            Resource resource = new UrlResource(path.toUri());
            
            // 检查文件是否存在
            if (!resource.exists()) {
                return ResponseEntity.notFound().build();
            }
            
            // 设置文件名编码，解决中文文件名问题
            String encodedFileName = URLEncoder.encode(exportRecord.getFileName(), StandardCharsets.UTF_8.toString())
                    .replaceAll("\\+", "%20");
            
            // 设置响应头
            return ResponseEntity.ok()
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + encodedFileName)
                    .body(resource);
            
        } catch (Exception e) {
            log.error("下载导出文件失败: " + e.getMessage(), e);
            return ResponseEntity.internalServerError().build();
        }
    }
} 